package com.gzy.android_douban.ui.login;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.appcompat.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.gzy.android_douban.R;
import com.gzy.android_douban.data.api.ApiService;
import com.gzy.android_douban.data.model.MovieModel;
import com.gzy.android_douban.data.model.UsersLoginModel;
import com.gzy.android_douban.data.model.ValidateCodeModel;
import com.gzy.android_douban.ui.MainActivity;
import com.gzy.android_douban.ui.home.SearchActivity;
import com.gzy.android_douban.ui.login.LoginViewModel;
import com.gzy.android_douban.ui.login.LoginViewModelFactory;
import com.gzy.android_douban.databinding.ActivityLoginBinding;
import com.gzy.network.NetworkApi;
import com.gzy.network.observer.BaseObserver;

import okhttp3.ResponseBody;

public class LoginActivity extends AppCompatActivity {

  private LoginViewModel loginViewModel;
  private ActivityLoginBinding binding;
  private ValidateCodeModel validateCodeModelb;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    binding = ActivityLoginBinding.inflate(getLayoutInflater());
    setContentView(binding.getRoot());
    initData();

    initClick();

    Intent intent = getIntent();
    System.out.println("注册页返回数据" + intent.getStringExtra("username"));
    binding.edUsername.setText(intent.getStringExtra("username"));

//    loginViewModel = new ViewModelProvider(this, new LoginViewModelFactory())
//        .get(LoginViewModel.class);
//
//
//    loginViewModel.getLoginFormState().observe(this, new Observer<LoginFormState>() {
//      @Override
//      public void onChanged(@Nullable LoginFormState loginFormState) {
//        if (loginFormState == null) {
//          return;
//        }
//        binding.login.setEnabled(loginFormState.isDataValid());
//        if (loginFormState.getUsernameError() != null) {
//          binding.edUsername.setError(getString(loginFormState.getUsernameError()));
//        }
//        if (loginFormState.getPasswordError() != null) {
//          binding.edPassword.setError(getString(loginFormState.getPasswordError()));
//        }
//      }
//    });
//
//    loginViewModel.getLoginResult().observe(this, new Observer<LoginResult>() {
//      @Override
//      public void onChanged(@Nullable LoginResult loginResult) {
//        if (loginResult == null) {
//          return;
//        }
//        binding.loading.setVisibility(View.GONE);
//        if (loginResult.getError() != null) {
//          showLoginFailed(loginResult.getError());
//        }
//        if (loginResult.getSuccess() != null) {
//          updateUiWithUser(loginResult.getSuccess());
//        }
//        setResult(Activity.RESULT_OK);
//
//        //Complete and destroy login activity once successful
//        finish();
//      }
//    });
//
//    TextWatcher afterTextChangedListener = new TextWatcher() {
//      @Override
//      public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//        Log.i("官场这", "2|" + "s:" + s + "|start:" + start + "|count:" + count + "|after:" + after);
//        // ignore
//      }
//
//      @Override
//      public void onTextChanged(CharSequence s, int start, int before, int count) {
//        Log.i("官场这", "onTextChanged|" + "s:" + s + "|start:" + start + "|before:" + before + "|count:" + count);
//        // ignore
//      }
//
//      @Override
//      public void afterTextChanged(Editable s) {
//        Log.i("官场这", "afterTextChanged|" + "s:" + s);
//        loginViewModel.loginDataChanged(binding.edUsername.getText().toString(),
//            binding.edPassword.getText().toString());
//      }
//    };
//
//    binding.edUsername.addTextChangedListener(afterTextChangedListener);
//    binding.edPassword.addTextChangedListener(afterTextChangedListener);
//
//    binding.edPassword.setOnEditorActionListener(new TextView.OnEditorActionListener() {
//
//      @Override
//      public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
//        if (actionId == EditorInfo.IME_ACTION_DONE) {
//          loginViewModel.login(binding.edUsername.getText().toString(),
//              binding.edPassword.getText().toString());
//        }
//        return false;
//      }
//    });
//
//    binding.login.setOnClickListener(new View.OnClickListener() {
//      @Override
//      public void onClick(View v) {
//        binding.loading.setVisibility(View.VISIBLE);
//        loginViewModel.login(binding.edUsername.getText().toString(),
//            binding.edPassword.getText().toString());
//      }
//    });
  }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


    }
    private void initClick() {
    binding.login.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        if (!binding.edUsername.getText().toString().equals("") && !binding.edPassword.getText().toString().equals("") && !binding.edValidateCode.getText().toString().equals("")){
            NetworkApi.createService(ApiService.class)
                    .postLoginApi(binding.edPassword.getText().toString(),validateCodeModelb.getData().getRandomCode(),binding.edUsername.getText().toString(),Integer.parseInt(binding.edValidateCode.getText().toString()))
                    .compose(NetworkApi.applySchedulers(new BaseObserver<UsersLoginModel>() {

                        @Override
                        public void onSuccess(UsersLoginModel usersLoginModel) {
                            System.out.println(usersLoginModel);
                            SharedPreferences settings = getSharedPreferences("userToken",0);
                            SharedPreferences.Editor editor = settings.edit();
                            editor.putString("token",usersLoginModel.getData().getToken());
                            editor.commit();

                            // 取数据
                            System.out.println(settings.getString("token","").toString());

                            // 跳转到首页
                            Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                            startActivity(intent);
                        }

                        @Override
                        public void onFailure(Throwable e) {
                            System.out.println("请求失败");
                        }
                    }));
        }else {
          Toast.makeText(LoginActivity.this, "请输入用户名或密码", Toast.LENGTH_SHORT).show();
        }
      }
    });
    binding.tvToRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(LoginActivity.this, "注册", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
            startActivity(intent);
        }
    });
  }

  private void initData() {
    getValidateCode();
  }

  // 获取验证码
  public void getValidateCode(){
    NetworkApi.createService(ApiService.class)
            .getValidateCodeApi()
            .compose(NetworkApi.applySchedulers(new BaseObserver<ValidateCodeModel>() {

              @Override
              public void onSuccess(ValidateCodeModel validateCodeModel) {
                System.out.println("验证码请求成功");
                validateCodeModelb = validateCodeModel;
                System.out.println("validateCodeModelb:" + validateCodeModelb);
                System.out.println("getValidateCode" + validateCodeModel);
                getValidateCodeImage(validateCodeModel.getData().getRandomCode().toString());
              }

              @Override
              public void onFailure(Throwable e) {
                System.out.println("请求失败");
              }
            }));
  }

  //获取验证码图片
  public void  getValidateCodeImage(String randomCode){
    NetworkApi.createService(ApiService.class)
            .getValidateCodeImageApi(randomCode)
            .compose(NetworkApi.applySchedulers(new BaseObserver<ResponseBody>() {

              @Override
              public void onSuccess(ResponseBody responseBody) {
                System.out.println("验证码照片请求成功");
//                System.out.println("getValidateCodeImage:" + responseBody);
                  String url = "http://124.221.182.86:8877/image/validate-code/" + randomCode;
//                binding.imgValidateCode.setImageResource(responseBody);
                  Glide.with(LoginActivity.this)/*在哪个页面显示*/
                          .load(url)/*加载的网络图片地址*/
                          .placeholder(R.drawable.back)/*预显示占位图*/
                          .dontAnimate()/*不进行图片的拉伸*/
                          .override(750, 150)/*强制让图片原大小显示*/
                          .into(binding.imgValidateCode);/*在ImageView中显示*/
              }

              @Override
              public void onFailure(Throwable e) {
                System.out.println("请求失败");
              }
            }));
  }

  private void updateUiWithUser(LoggedInUserView model) {
    String welcome = getString(R.string.welcome) + model.getLoggedInUser().getUserId();
    // TODO : initiate successful logged in experience
    Toast.makeText(getApplicationContext(), welcome, Toast.LENGTH_LONG).show();
  }

  private void showLoginFailed(@StringRes Integer errorString) {
    Toast.makeText(getApplicationContext(), errorString, Toast.LENGTH_SHORT).show();
  }
}